// 只允许输入小数
import 'package:flutter/services.dart';

class UseNumberTextInputFormatter extends TextInputFormatter {
  final double defaultDouble;
  final int digits;
  final double maxValue;
  UseNumberTextInputFormatter({this.defaultDouble = 0.01, this.digits = 2, this.maxValue = double.maxFinite});

  double strToFloat(String str) {
    try {
      return double.parse(str);
    } catch (e) {
      return defaultDouble;
    }
  }

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    String value = newValue.text;
    int selectionIndex = newValue.selection.extent.offset;
    //删除“.”后面超过2位后的数据
    if (value.contains(".")) {
      if (value.length - 1 - value.indexOf(".") > digits) {
        value = value.substring(0, value.indexOf(".") + digits+1);
        selectionIndex = value.length;
      }
    }
    if (value == ".") {
      value = "0.";
      selectionIndex++;
    } else if (value != "" && value != defaultDouble.toString() && strToFloat(value) == defaultDouble) {
      value = oldValue.text;
      selectionIndex = oldValue.selection.extent.offset;

    } else if(value != "" && maxValue != double.maxFinite){
      if(strToFloat(value) > maxValue){
        value = oldValue.text;
        selectionIndex = oldValue.selection.extent.offset;
      }
    }
    return new TextEditingValue(
      text: value,
      selection: new TextSelection.collapsed(offset: selectionIndex),
    );
  }
}